package com.uff.hmstpa.model.persistence.impl;

import com.uff.hmstpa.controller.impl.ScheduleSystemControllerImpl;
import com.uff.hmstpa.model.domain.valueobject.Appointment;
import com.uff.hmstpa.model.persistence.AbstractModelDAO;
import com.uff.hmstpa.model.persistence.AppointmentDAO;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.joda.time.DateTime;
import org.springframework.jdbc.core.RowMapper;

public class AppointmentDAOImpl extends AbstractModelDAO implements AppointmentDAO {

    private static AppointmentDAOImpl SOLE_INSTANCE;

    private AppointmentDAOImpl() {
        super();
    }

    public static AppointmentDAO getInstance() {
        if (SOLE_INSTANCE == null) {
            SOLE_INSTANCE = new AppointmentDAOImpl();
        }
        return SOLE_INSTANCE;
    }

    public void persist(String crm, String cpf, DateTime time) {
        jdbcTemplate.update("INSERT INTO appointment(time, doctor, patient) VALUE (?, ?, ?)", crm, cpf, time);
    }

    public List<Appointment> loadAppointments(String doctorCRM) {
        if (doctorCRM != null) {
            return jdbcTemplate.query("SELECT * FROM appointment WHERE doctor = ?", new Object[]{doctorCRM}, new AppointmentMapper());
        } else {
            return jdbcTemplate.query("SELECT * FROM appointment", new AppointmentMapper());
        }
    }

    public void delete(String crm, String cpf, DateTime time) {
        //TODO delete appointment
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public Appointment retrieve(String crm, String cpf, DateTime time) {
        return jdbcTemplate.queryForObject("SELECT * FROM appointment WHERE time = ? AND crm = ? AND cpf = ?", new Object[]{crm, cpf, time}, new AppointmentMapper());
    }

    private static final class AppointmentMapper implements RowMapper<Appointment> {

        public Appointment mapRow(ResultSet rs, int rowNum) throws SQLException {
            Appointment appointment = new Appointment();
            appointment.setDoctor(DoctorDAOImpl.getInstance().retrieve(rs.getString("doctor")));
            appointment.setPatient(PatientDAOImpl.getInstance().retrieve(rs.getString("patient")));
            appointment.setTime(new DateTime(rs.getDate("time").getTime()));
            return appointment;
        }
    }
}
